<?php
/**
 * 【重要】database
 * Enter description here ...
 * @author hxm
 *
 */
class CPdo {
	
	public static $db      = null;//db配置
	
	public static $table   = null;//当前call表
		
	public static $pdo     = null;
	
	public function __construct() {
		
		self::$db = SoftBase::$config['db'];
		
		try {
			self::$pdo =  new PDO(
				self::$db['connectionString'],
				self::$db['username'],
				self::$db['password'], 
				array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ".self::$db['charset'],PDO::FETCH_ASSOC=>true));	
		
		} catch (Exception $e) {
			
			exit('数据库连接失败，错误信息：'. $e->getMessage());
		}
	}
	
	/**
	 * 执行力
	 * Enter description here ...
	 * @param unknown_type $sql
	 */
	public function query($sql) {
		
	  	return self::$pdo->query($sql);
	}
	
	/**
	 * 执行力
	 * Enter description here ...
	 * @param unknown_type $sql
	 */
	public function exec($sql) {
		
	  	return self::$pdo->exec($sql);
	}
	
	/**
	 * 表组合
	 * Enter description here ...
	 */
	public function tablePrefix() {
		
		if(SoftBase::$config['db']['tablePrefix']) {
			
			$table = SoftBase::$config['db']['tablePrefix'].self::$table;
		} else {
			$table = self::$table;
		}
		return $table; 
	}
	
	/**
	 * 查询单条数据
	 * Enter description here ...
	 $condition = "where username='好啦'";
	 $params    = array(
		'col'   => 'u.id,u.username',
		'group' => 'group by username',
		'order' => 'order by u.id desc',
	 );
	 */
	public function find($condition='',$params=array()) {
		
		$sql = sprintf("SELECT %s FROM %s %s %s %s Limit 1",$params['col'],$this->tablePrefix(),$condition,$params['group'],$params['order']);
		
		return self::$pdo = $this->query($sql)->fetch();
	}
	
	/**
	 * 查询多条数据
	 * Enter description here ...
	 $condition = "where username='好啦'";
	 $params    = array(
		'col'   => 'u.id,u.username',
		'group' => 'group by username',
		'order' => 'order by u.id desc',
		'limit' => 'limit 10',//findAll 才能使用
		'where' => 'where id in()',
	 );
	 */
	public function findAll($condition,$params=array()) {
		
		$sql = sprintf("SELECT %s FROM %s %s %s %s",$params['col'],$this->tablePrefix(),$params['where'],$params['group'],$params['order'],$params['limit']);
		
		return self::$pdo = $this->query($sql)->fetchAll();
	}
	
	/**
	 * 组合查询
	 * Enter description here ...
	 $params    = array(
		'table' => 'huju_user as u',
		'col'   => 'u.id,u.username',
		'group' => 'group by username',
		'order' => 'order by u.id desc',
		'limit' => 'limit 10',//findAll 才能使用
		'join'  => ' left join huju_order as s',
		'where' => 's.user_id = u.id l',
	 );
	 */
	public function combined($params=array()) {
		
		$sql = $this->where($params);
		
		return self::$pdo = $this->query($sql)->fetchAll();
		
	}
	
	/**
	 * 语句组合
	 * Enter description here ...
	 */
	public function where($params=array()) {
		if(!empty($params)) {
			$col   = !empty($params['col']) ? $params['col'] : '*';
			$join  = !empty($params['join'])? trim($params['join'],'').' on '.$params['where'] : '';
			$group = !empty($params['group'])? ' '.trim($params['group'],'') : '';
			$order = !empty($params['order'])? ' '.trim($params['order'],'') : '';
			$limit = !empty($params['limit'])? ' '.trim($params['limit'],'') : '';
			return  "SELECT {$col} FROM ".$params['table'].' '.$join.$group.$order.$limit;
		} else {
			return array();
		}
	}
	
	/**
	 * 修改
	 * Enter description here ...
	 */
	public function update($condition,$where) {
		
		$sql = "UPDATE `{$this->tablePrefix()}` SET " . $this->Udata($condition) . $this->date($where) . ";";
		
		return $this->exec($sql);
	}
	
	/**
	 * 删除
	 * Enter description here ...
	 */
	public function del() {
		$sql = "DELETE FROM `{$this->tablePrefix()}` ;";
	}
	
	/**
	 * 添加
	 * Enter description here ...
	 */
	public function add($date) {
		
		$sql = "INSERT INTO `{$this->tablePrefix()}` " . $this->Upvalues ( $date ) . ";";
		
		return $this->exec($sql) ? self::$pdo->lastInsertId () : false;
	}
	
	/**
	 * 处理插入数据
	 */
	private function Uinsert($date) {
		if (is_array ( $date )) {
			foreach ( $date as $key => $row ) {
				$k [] = "`" . $key . "`";
				$r [] = "'" . $row . "'";
			}
			$k = "(" . implode ( ',', $k ) . ")";
			$r = "(" . implode ( ',', $r ) . ")";
			return $k . ' VALUES ' . $r;
		} else {
			return false;
		}
	}
	
	
	/**
	 * 处理数据
	 */
	private function date($date) {
		if (is_array ( $date )) {
			foreach ( $date as $key => $row ) {
				$d [] = " WHERE `" . $key . "`='" . $row . "'";
			}
			return implode ( ',', $d );
		} else {
			return $date;
		}
	}
	
	/**
	 * 处理修改数据
	 * Enter description here ...
	 */
	private function Udata($date) {
		if(is_array($date)) {
			foreach($date as $key=>$row) {
				$d [] = " `" . $key . "`='" . $row . "'";
			}
			return implode ( ',', $d );
		} else {
			return false;
		}
	}
}